package cn.yujiago.shiro.service.impl;

import cn.yujiago.shiro.domain.MenuDO;
import cn.yujiago.shiro.domain.RoleDO;
import cn.yujiago.shiro.mapper.MenuMapper;
import cn.yujiago.shiro.mapper.RoleMapper;
import cn.yujiago.shiro.pojo.AuthNode;
import cn.yujiago.shiro.pojo.LayuiResult;
import cn.yujiago.shiro.pojo.LayuiTableResult;
import cn.yujiago.shiro.service.MenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PageHelper pageHelper;

    @Override
    public Set<String> getPermsByUserId(Long userId) {

        Set<String> permSet = new HashSet<>();

        // 根据用户ID查询角色，再根据角色ID查询相应的权限
        List<RoleDO> roles = roleMapper.selectRoles(userId);

        for(RoleDO role : roles){
            List<String> permList = menuMapper.selectPerms(role.getId());
            for(String perm : permList){
                permSet.add(perm);
            }
        }
        return permSet;
    }

    @Override
    public LayuiTableResult<AuthNode> getAuthTreeByUserId(Long userId) {

        // 查出所有菜单
        List<MenuDO> menuDOS = menuMapper.selectAll();

        // 查出用户所拥有权限
        Set<String> perms = this.getPermsByUserId(userId);
        // 转换成权限树的初始链表
        List<AuthNode> rootList = new ArrayList<>();
        // 遍历后拥有树结构的链表
        List<AuthNode> nodeList = new ArrayList<>();

        for (MenuDO menu : menuDOS){
            if(perms.contains(menu.getPerms())){
                rootList.add(new AuthNode(menu.getId(), menu.getParentId(), menu.getName(), true));
            }else{
                rootList.add(new AuthNode(menu.getId(), menu.getParentId(), menu.getName(), false));
            }
        }
        // 找出父节点
        for (AuthNode node : rootList){
            if(node.getParentId() != null && node.getParentId() == 0){
                nodeList.add(node);
            }
        }
        // 为父节点添加子菜单，递归调用
        for(AuthNode node : nodeList){
            node.setList(getChild(node.getValue(), rootList));
        }

        LayuiTableResult<AuthNode> result = new LayuiTableResult<>();
        result.setCode(0);
        result.setMsg("查询成功！");
        result.setData(nodeList);

        return result;
    }

    @Override
    public LayuiTableResult<AuthNode> getAuthTreeByRoleId(Long roleId) {

        // 查出所有菜单
        List<MenuDO> menuDOS = menuMapper.selectAll();

        // 查出角色所拥有的权限
        List<String> perms = menuMapper.selectPerms(roleId);
        // 转换成权限树的初始链表
        List<AuthNode> rootList = new ArrayList<>();
        // 遍历后拥有树结构的链表
        List<AuthNode> nodeList = new ArrayList<>();

        for (MenuDO menu : menuDOS){
            if(perms.contains(menu.getPerms())){
                rootList.add(new AuthNode(menu.getId(), menu.getParentId(), menu.getName(), true));
            }else{
                rootList.add(new AuthNode(menu.getId(), menu.getParentId(), menu.getName(), false));
            }
        }
        // 找出父节点
        for (AuthNode node : rootList){
            if(node.getParentId() != null && node.getParentId() == 0){
                nodeList.add(node);
            }
        }
        // 为父节点添加子菜单，递归调用
        for(AuthNode node : nodeList){
            node.setList(getChild(node.getValue(), rootList));
        }

        LayuiTableResult<AuthNode> result = new LayuiTableResult<>();
        result.setCode(0);
        result.setMsg("查询成功！");
        result.setData(nodeList);

        return result;
    }

    @Override
    public LayuiTableResult<MenuDO> getMenusByCondition(int page, int limit) {
        // 1、设置分页信息，包括当前页数和每页显示的总计数
        pageHelper.startPage(page, limit);

        List<MenuDO> menuDOS = menuMapper.selectAll();

        PageInfo<MenuDO> pageInfo = new PageInfo<>(menuDOS);

        LayuiTableResult<MenuDO> result = new LayuiTableResult<>();
        result.setCode(0);
        result.setMsg("查询成功！");
        result.setData(menuDOS);
        result.setCount(pageInfo.getSize());

        return result;
    }

    @Override
    public LayuiResult updateRoleMenu(Long roleId, List<Long> menuIds) {

        // 删除该角色的权限
        menuMapper.deleteRoleMenuByRoleId(roleId);
        if(menuIds != null){
            // 插入该角色的最新所有权限
            menuMapper.insertRoleMenu(roleId, menuIds);
        }
        return LayuiResult.build(200, "执行成功！");
    }

    private List<AuthNode> getChild(Long id, List<AuthNode> rootList){
        // 子菜单
        List<AuthNode> childList = new ArrayList<>();
        for (AuthNode node : rootList) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (node.getParentId() != null && node.getParentId() != 0) {
                if (node.getParentId().equals(id)) {
                    childList.add(node);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (AuthNode node : childList) {// 没有url子菜单还有子菜单
            if (node.getParentId() != null && node.getParentId() != 0) {
                // 递归
                node.setList(getChild(node.getValue(), rootList));
            }
        }
         // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
